<template>
  <div class="search-input" :class="{ 'is-focused': focused }">
    <el-input
      ref="input"
      v-model="searchValue"
      :placeholder="placeholder"
      :size="size"
      :disabled="disabled"
      :clearable="clearable"
      @input="handleInput"
      @focus="handleFocus"
      @blur="handleBlur"
      @keyup.enter="handleSearch"
      @clear="handleClear"
      class="search-input-field"
    >
      <template #prefix>
        <i class="el-icon-search search-icon"></i>
      </template>
      
      <template #suffix v-if="showSearchButton">
        <el-button
          type="primary"
          size="mini"
          @click="handleSearch"
          :disabled="disabled || !searchValue.trim()"
          class="search-button"
        >
          搜索
        </el-button>
      </template>
    </el-input>
    
    <!-- 搜索建议 -->
    <div 
      v-if="showSuggestions && suggestions.length > 0"
      class="search-suggestions"
    >
      <div
        v-for="(suggestion, index) in suggestions"
        :key="index"
        class="suggestion-item"
        :class="{ 'is-active': index === activeSuggestionIndex }"
        @click="selectSuggestion(suggestion)"
        @mouseenter="activeSuggestionIndex = index"
      >
        <i class="el-icon-search suggestion-icon"></i>
        <span class="suggestion-text">{{ suggestion }}</span>
      </div>
    </div>
    
    <!-- 历史搜索 -->
    <div
      v-if="showHistory && searchHistory.length > 0 && !searchValue.trim()"
      class="search-history"
    >
      <div class="history-header">
        <span class="history-title">搜索历史</span>
        <el-button
          type="text"
          size="mini"
          @click="clearHistory"
          class="clear-history-btn"
        >
          清空
        </el-button>
      </div>
      
      <div class="history-items">
        <el-tag
          v-for="(item, index) in searchHistory"
          :key="index"
          size="small"
          @click="selectHistory(item)"
          @close="removeHistory(index)"
          closable
          class="history-tag"
        >
          {{ item }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script>
import { debounce } from '@/utils/helpers'

export default {
  name: 'SearchInput',
  
  props: {
    // 搜索值
    value: {
      type: String,
      default: ''
    },
    
    // 占位符
    placeholder: {
      type: String,
      default: '请输入搜索关键词'
    },
    
    // 尺寸
    size: {
      type: String,
      default: 'medium',
      validator: value => ['large', 'medium', 'small', 'mini'].includes(value)
    },
    
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    
    // 是否可清空
    clearable: {
      type: Boolean,
      default: true
    },
    
    // 是否显示搜索按钮
    showSearchButton: {
      type: Boolean,
      default: false
    },
    
    // 搜索建议
    suggestions: {
      type: Array,
      default: () => []
    },
    
    // 是否显示搜索建议
    showSuggestions: {
      type: Boolean,
      default: true
    },
    
    // 是否显示搜索历史
    showHistory: {
      type: Boolean,
      default: true
    },
    
    // 搜索历史存储键
    historyKey: {
      type: String,
      default: 'search_history'
    },
    
    // 最大历史记录数
    maxHistory: {
      type: Number,
      default: 10
    },
    
    // 防抖延迟
    debounceDelay: {
      type: Number,
      default: 300
    }
  },
  
  data() {
    return {
      searchValue: this.value,
      focused: false,
      activeSuggestionIndex: -1,
      searchHistory: []
    }
  },
  
  watch: {
    value(newVal) {
      this.searchValue = newVal
    },
    
    searchValue(newVal) {
      this.$emit('input', newVal)
      this.debouncedSearch(newVal)
    }
  },
  
  created() {
    // 创建防抖搜索函数
    this.debouncedSearch = debounce(this.emitSearch, this.debounceDelay)
    
    // 加载搜索历史
    this.loadHistory()
    
    // 监听键盘事件
    this.addKeyboardListeners()
  },
  
  beforeDestroy() {
    this.removeKeyboardListeners()
  },
  
  methods: {
    // 处理输入
    handleInput() {
      this.activeSuggestionIndex = -1
    },
    
    // 处理焦点
    handleFocus() {
      this.focused = true
      this.$emit('focus')
    },
    
    // 处理失焦
    handleBlur() {
      // 延迟失焦，以便点击建议项
      setTimeout(() => {
        this.focused = false
        this.activeSuggestionIndex = -1
        this.$emit('blur')
      }, 200)
    },
    
    // 处理搜索
    handleSearch() {
      const value = this.searchValue.trim()
      if (value) {
        this.addToHistory(value)
        this.$emit('search', value)
        this.focused = false
      }
    },
    
    // 处理清空
    handleClear() {
      this.$emit('clear')
      this.$emit('search', '')
    },
    
    // 发送搜索事件
    emitSearch(value) {
      this.$emit('input-change', value)
    },
    
    // 选择建议
    selectSuggestion(suggestion) {
      this.searchValue = suggestion
      this.handleSearch()
    },
    
    // 选择历史记录
    selectHistory(item) {
      this.searchValue = item
      this.handleSearch()
    },
    
    // 添加到历史记录
    addToHistory(value) {
      if (!this.showHistory) return
      
      // 移除重复项
      const index = this.searchHistory.indexOf(value)
      if (index > -1) {
        this.searchHistory.splice(index, 1)
      }
      
      // 添加到开头
      this.searchHistory.unshift(value)
      
      // 限制数量
      if (this.searchHistory.length > this.maxHistory) {
        this.searchHistory = this.searchHistory.slice(0, this.maxHistory)
      }
      
      // 保存到本地存储
      this.saveHistory()
    },
    
    // 移除历史记录
    removeHistory(index) {
      this.searchHistory.splice(index, 1)
      this.saveHistory()
    },
    
    // 清空历史记录
    clearHistory() {
      this.searchHistory = []
      this.saveHistory()
    },
    
    // 加载历史记录
    loadHistory() {
      try {
        const history = localStorage.getItem(this.historyKey)
        if (history) {
          this.searchHistory = JSON.parse(history)
        }
      } catch (error) {
        console.error('加载搜索历史失败:', error)
      }
    },
    
    // 保存历史记录
    saveHistory() {
      try {
        localStorage.setItem(this.historyKey, JSON.stringify(this.searchHistory))
      } catch (error) {
        console.error('保存搜索历史失败:', error)
      }
    },
    
    // 添加键盘监听
    addKeyboardListeners() {
      this.keyboardHandler = (e) => {
        if (!this.focused) return
        
        const suggestionsCount = this.suggestions.length
        
        switch (e.key) {
          case 'ArrowDown':
            e.preventDefault()
            if (suggestionsCount > 0) {
              this.activeSuggestionIndex = Math.min(
                this.activeSuggestionIndex + 1,
                suggestionsCount - 1
              )
            }
            break
            
          case 'ArrowUp':
            e.preventDefault()
            if (suggestionsCount > 0) {
              this.activeSuggestionIndex = Math.max(
                this.activeSuggestionIndex - 1,
                -1
              )
            }
            break
            
          case 'Enter':
            e.preventDefault()
            if (this.activeSuggestionIndex >= 0 && this.activeSuggestionIndex < suggestionsCount) {
              this.selectSuggestion(this.suggestions[this.activeSuggestionIndex])
            } else {
              this.handleSearch()
            }
            break
            
          case 'Escape':
            this.focused = false
            this.$refs.input.blur()
            break
        }
      }
      
      document.addEventListener('keydown', this.keyboardHandler)
    },
    
    // 移除键盘监听
    removeKeyboardListeners() {
      if (this.keyboardHandler) {
        document.removeEventListener('keydown', this.keyboardHandler)
      }
    },
    
    // 聚焦输入框
    focus() {
      this.$refs.input.focus()
    },
    
    // 失焦输入框
    blur() {
      this.$refs.input.blur()
    }
  }
}
</script>

<style lang="scss" scoped>
.search-input {
  position: relative;
  
  .search-input-field {
    :deep(.el-input__inner) {
      padding-left: 35px;
    }
    
    .search-icon {
      color: #c0c4cc;
    }
    
    .search-button {
      margin-right: 5px;
    }
  }
}

.search-suggestions,
.search-history {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-top: none;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 300px;
  overflow-y: auto;
}

.search-suggestions {
  .suggestion-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    cursor: pointer;
    transition: background-color 0.2s;
    
    &:hover,
    &.is-active {
      background-color: #f5f7fa;
    }
    
    .suggestion-icon {
      margin-right: 8px;
      color: #c0c4cc;
      font-size: 14px;
    }
    
    .suggestion-text {
      flex: 1;
      font-size: 14px;
      color: #606266;
    }
  }
}

.search-history {
  padding: 12px;
  
  .history-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
    
    .history-title {
      font-size: 12px;
      color: #909399;
      font-weight: 500;
    }
    
    .clear-history-btn {
      padding: 0;
      font-size: 12px;
      color: #909399;
      
      &:hover {
        color: #409eff;
      }
    }
  }
  
  .history-items {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    
    .history-tag {
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background-color: #ecf5ff;
        border-color: #b3d8ff;
        color: #409eff;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .search-suggestions,
  .search-history {
    max-height: 200px;
  }
  
  .search-history {
    .history-items {
      .history-tag {
        font-size: 12px;
      }
    }
  }
}
</style>